package com.qf.forumproject.loginAndRegister.service.Impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.forumproject.entity.QfUser;
import com.qf.forumproject.loginAndRegister.dao.QfUserDao;
import com.qf.forumproject.loginAndRegister.service.QfUserService;
import com.qf.forumproject.utils.RegisterVo;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;
import java.util.UUID;


/**
 * (QfUser表)服务实现类
 *
 * @author protagonist
 * @since 2022-07-26 08:52:49
 */
@Service("qfUserServiceImpl")
@Slf4j
public class QfUserServiceImpl extends ServiceImpl<QfUserDao,QfUser> implements QfUserService {
    @Resource
    private QfUserDao qfUserDao;

    private String filedir = "/Users/manchi520/Desktop/qianfeng/forumProject/src/main/java/com/qf/forumproject/upload/";

    @SneakyThrows
    @Override
    public QfUser insert(RegisterVo registerVo) {

        //1、处理文件路径
        //获取文件名
        String originalFilename = registerVo.getAvatar().getOriginalFilename();
        //获取UUID前缀，并将格式中的"-"去掉
        String prefix = UUID.randomUUID().toString().replaceAll("-", "");
        //拼出最终文件名
        String finalFileName = prefix + "_" + originalFilename;
        //拿到最终需要上传的文件路径
        String finalFilePath = filedir + finalFileName;
        //上传文件
        registerVo.getAvatar().transferTo(new File(finalFilePath));
        log.debug("文件上传成功，路径为：{}", finalFilePath);

        QfUser user = new QfUser();
        user.setGmtCreate(DateUtil.date());
        user.setAvatar(finalFilePath);

        //1. 产生一个随机盐
        final String salt = RandomUtil.randomString(8);
        //2. 生成密码
        final Md5Hash md5Hash = new Md5Hash(registerVo.getPassword(), salt, 1024);
        final String md5password = md5Hash.toHex();
        //3. 入库

        user.setSalt(salt);

        BeanUtils.copyProperties(registerVo,user);

        user.setPassword(md5password);
        int i = qfUserDao.insert(user);
        if (i > 0){
            return user;
        }
        return null;
    }
}



